<!--
  -    Copyright (c) 2018-2025, infomng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: infomng
  -->
<template>
  <div class="execution">
    <basic-container>
      <div class="form-container">
        <el-form ref="form"
                 v-loading="loading"
                 element-loading-text="正在提交..."
                 element-loading-spinner="el-icon-loading"
                 :model="form" :rules="rules" style="width: 100%;height: fit-content;margin: 0 30px;padding: 30px;box-shadow: 0 2px 12px 0 rgb(233,236,230)" label-width="135px" label-position="right">
  <h2 style="width:100%;text-align: center;margin-bottom: 50px">生产报工</h2>
  <div>
    <el-row>
      <el-col :span="6">
        <el-form-item label="车间：" prop="workshopId">
          <el-select v-model="form.workshopId" placeholder="请选择车间"  @clear="clearWorkshop" filterable clearable style="width:100%;">
            <el-option
              @click.native="workshopChange(item)"
              v-for="item in workshopList"
              :key="item.id"
              :label="item.workshopName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="产线：" prop="productLineId">
          <el-select  v-model="form.productLineId" @clear="clearLine" :disabled="validatenull(form.workshopId)" clearable filterable placeholder="请选择产线" style="width: 100%">
            <el-option
              @click.native="chooseLine(item)"
              v-for="item in lineList"
              v-if="item.workshopId===form.workshopId"
              :label="item.realityLineName"
              :value="item.id"
              :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="工单：" prop="docNo">
          <el-select  v-model="form.docNo" filterable placeholder="请选择工单" @clear="clearDocNo" clearable :disabled="validatenull(form.productLineId)" style="width: 100%">
            <el-option
              @click.native="chooseDocNo(item)"
              v-for="item in docNoList"
              :label="item.docNo"
              :value="item.docNo"
              :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="品号：" >
          <el-input v-model="form.itemCode" disabled />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="6">
        <el-form-item label="工位：" prop="workPositionId">
          <el-select  v-model="form.workPositionId" filterable placeholder="请选择工位" :disabled="form.productLineId==null" style="width: 100%">
            <el-option
              @click.native="chooseWorkstation(item)"
              v-for="item in lineDetailsList"
              :label="item.workPositionName"
              :value="item.workPositionId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="工段：">
          <el-input v-model="form.workshopSection" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="工序：" prop="processId">
          <el-select  v-model="form.processId" filterable placeholder="请选择工序" :disabled="form.workPositionId==null" style="width: 100%">
            <el-option
              @click.native="chooseProcess(item)"
              v-for="item in processList"
              :label="item.processName"
              :value="item.id"
              :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="工位状态："prop="">
          <el-select  v-model="form.moStatus" filterable  placeholder="请选择当前工序状态"  style="width: 100%">
            <el-option
              v-for="item in options"
              :label="item.label"
              :value="item.value"
              :key="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="报工时间：">
          <el-date-picker  v-model="form.reportTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择报工时间" :default-value="new Date()" style="width: 100%">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="8">
        <el-form-item label="在制品完成数量：" prop="workInProgressQty">
          <el-input-number v-model="form.workInProgressQty" :min="0" label="请输入在制品完成数量" :controls="false"></el-input-number>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="在制品报废数量：" prop="workInProgressScrapQty" >
          <el-input-number v-model="form.workInProgressScrapQty" :min="0" label="请输入在制品报废数量" :controls="false"></el-input-number>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="返工数量：" prop="reworkQty" >
          <el-input-number v-model="form.reworkQty" :min="0" label="请输入返工数量" :controls="false"></el-input-number>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="!validatenull(badItem)">
      <el-col :span="8">
        <el-form-item label="在制品报废项：">
          <el-row v-for="(item, index) in zzpItems" :key="index">
            <el-col :span="18" @click.native="increment('zzp', index)">
              <el-button type="text" style="font-size: 14px;">{{ item.scrapReason }}</el-button>
            </el-col>
            <el-col :span="2">
              <span>{{ item.workInProgressScrapQty }}</span>
            </el-col>
            <el-col :span="4">
              <el-button @click="decrement('zzp', index)" type="danger" style="padding: 4px;" size="mini" circle icon="el-icon-minus"></el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="物料报废项：">
          <el-row v-for="(item, index) in wlItems" :key="index">
            <el-col :span="18"  @click.native="increment('wl', index)">
              <el-button type="text" style="font-size: 14px;">{{ item.scrapReason }}</el-button>
            </el-col>
            <el-col :span="2">
              <span>{{ item.scrapQty }}</span>
            </el-col>
            <el-col :span="4">
              <el-button @click="decrement('wl', index)" type="danger" style="padding: 4px;" size="mini" circle icon="el-icon-minus" ></el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="返工项：">
          <el-row v-for="(item, index) in reworkItems" :key="index">
            <el-col :span="18" @click.native="increment('rework', index)">
              <el-button type="text" style="font-size: 14px;" >{{ item.reworkReason }}</el-button>
            </el-col>
            <el-col :span="2">
              <span>{{ item.reworkQty }}</span>
            </el-col>
            <el-col :span="4">
              <el-button @click="decrement('rework', index)" type="danger" style="padding: 4px;"  size="mini" circle icon="el-icon-minus" ></el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row style="text-align: center;margin: 20px 0">
      <el-button type="primary"  @click="onSubmits" style="font-size: 16px">提交</el-button>
    </el-row>
  </div>
</el-form>
  </div>
  </basic-container>
  </div>
</template>

<script>
import {getLineList, getRealityProductLineDetailsList} from '@/api/pfoc/realityproductlinemain' //获取产线集合,根据产线ID获取产线工序集合
import {saveWorkOrderReport} from '@/api/workorder/workorderreport' //生产报工保存
import { getWorkshopList} from '@/api/pfoc/workshop' //获取全部车间
import {getWorkScheduleListByLineId} from "@/api/workorder/workscheduling";//根据产线ID获取产线下生产中的排产工单
import {getBadItemByProcessId} from "@/api/pfoc/pfocprocess"; //根据工序Id获取不良项
import { mapGetters } from 'vuex'


export default {
  name: 'workOrderReport',
  data() {
    return {
      loading: false,
      form:{
          productLineId:null,//产线ID
          productLineName:null,//产线名称
          docNo:null,//工单号
          workshopSection:null,//工段
          itemCode:null,//品号
          reportTime:null,//报工时间
          moStatus:null,//工单当前工序状态
          workInProgressScrapQty:undefined ,//报废数量
          workInProgressQty:undefined ,//已完成数量
          reworkQty:undefined ,//返工数量
          processName:null,//工序名称
          processId:null,//工序ID
          // workstation:null,//工位
          workPositionId:null,//工位ID
          workPositionName:null,//工位名称
          workshopId:null,//车间ID
          workshopName:null,//车间名称

        },
        wlItems:[],//物料报废原因以及对应数量集合
        zzpItems:[],//在制品报废原因以及对应数量集合
        reworkItems:[],//返工原因以及对应数量集合
        lineList:[],//产线集合
        lineInfo:{},//产线数据对象
        docNoList:[],//工单集合
        workOrderProductionList:[],//产线生产信息
        lineDetailsList:[],//产线详情集合
        processList:[],//工序集合
        // workstationList:[],//工序下工位集合
        workshopList:[],//车间数据集合
        badItem:null,//不良项集合
        options: [{
            value: '已完工',
            label: '已完工'
        }, {
            value: '未完工',
            label: '未完工',
        }],
        rules: {
            workshopId: [
              { required: true, message: '请选择车间', trigger: 'change' },
            ],
            productLineId: [
                { required: true, message: '请选择产线', trigger: 'change' },
            ],
            docNo: [
                { required: true, message: '请选择工单', trigger: 'change' }
            ],
            workPositionId: [
              { required: true, message: '请选择工位', trigger: 'change' }
            ],
           processId: [
                { required: true, message: '请选择工序', trigger: 'change' }
            ],
            workInProgressScrapQty: [
                {required: true, message: '请输入在制品报废数量', trigger: 'blur'  }
            ],
            workInProgressQty: [
                {required: true, message: '请输入在制品完成数量', trigger: 'blur'  }
            ],
            moStatus: [
                { required: true, message: '请选择工位状态', trigger: 'change' }
            ]
        }
    }
  },
  computed: {
    ...mapGetters(['permissions']),
  },
  created() {
      //获取产线集合
      this.getLineListData();
      //获取车间集合
      this.getWorkshopListData();
  },
  methods: {
      increment(type, index) {
        if (type === 'wl') {
          this.wlItems[index].scrapQty += 1;
        } else if (type === 'zzp') {
          this.zzpItems[index].workInProgressScrapQty += 1;
        } else if (type === 'rework') {
          this.reworkItems[index].reworkQty += 1;
        }
      },

      decrement(type, index) {
        if (type === 'wl' && this.wlItems[index].scrapQty > 0) {
          this.wlItems[index].scrapQty -= 1;
        } else if (type === 'zzp' && this.zzpItems[index].workInProgressScrapQty > 0) {
          this.zzpItems[index].workInProgressScrapQty -= 1;
        } else if (type === 'rework' && this.reworkItems[index].reworkQty > 0) {
          this.reworkItems[index].reworkQty -= 1;
        }
      },
      addReworkItem() {
        this.reworkItems.push({ reworkReason: '', reworkQty: 0 });
      },
      removeReworkItem(index) {
        // 根据下标删除对应的对象
        this.reworkItems.splice(index, 1);
      },
      addWuLiaoItem() {
        this.wlItems.push({ scrapReason: '', scrapQty: 0 });
      },
      removeWlItem(index) {
        // 根据下标删除对应的对象
        this.wlItems.splice(index, 1);
      },
      addZzpItem() {
        this.zzpItems.push({ scrapReason: '', workInProgressScrapQty: 0 });
      },
      removeZzpItem(index) {
        // 根据下标删除对应的对象
        this.zzpItems.splice(index, 1);
      },
      /**获取车间集合*/
      getWorkshopListData(){
        getWorkshopList().then(response => {
          this.workshopList=response.data.data;
        })
      },
      /**车间选择*/
      workshopChange(row){
        if(row.workshopName !== this.form.workshopName){
          this.clearWorkshop();
          this.form.workshopName = row.workshopName;//车间名称
        }
      },
      //清除车间
      clearWorkshop(){
        this.form.workshopName = null;
        this.form.productLineName =null;
        this.form.productLineId =null;
        this.form.docNo =null;
        this.form.itemCode =null;
        this.form.workshopSection =null;
        this.form.processName=null;
        this.form.processId =null;
        this.form.workPositionId =  null;//工位ID
        this.form.workPositionName =  null;//工位名称
      },
      //产线选择
      chooseLine(row){
          if(row.id !== this.lineInfo.id){
              this.clearLine();
              this.form.productLineId = row.id;//产线ID
              this.form.productLineName = row.realityLineName;//产线名称
              this.lineInfo = {...row};//当前选择的产线对象
              this.getList();//获取当前产线下未完工的排产工单
          }
      },
      //清除产线
      clearLine(){
        this.form.productLineName =null;
        this.form.productLineId =null;
        this.form.docNo =null;
        this.form.itemCode =null;
        this.form.workshopSection =null;
        this.form.processName=null;
        this.form.processId =null;
        this.form.workPositionId =  null;//工位ID
        this.form.workPositionName =  null;//工位名称
      },
      //工单选择
      chooseDocNo(row){
          this.clearDocNo()
          if(this.validatenull(this.form.docNo)){
              this.form.itemCode=null;
          }else{
              this.form.itemCode=row.itemCode;
          }
      },
      //工单清除
      clearDocNo(){
        this.form.itemCode=null;
        this.form.workshopSection =null;
        this.form.processName=null;
        this.form.processId =null;
        this.form.workPositionId =  null;//工位ID
        this.form.workPositionName =  null;//工位名称
      },
      //获取产线集合
      getLineListData(){
          getLineList().then(response => {
              this.lineList = response.data.data;
          })
      },
      // 工单排序列表查询
      getList() {
          if(this.validatenull(this.form.productLineId)){
              this.$message.warning("请选择产线。")
              return;
          }
          this.tableLoading = true
          //根据产线ID查询产线下未完工的排产工单
          var obj = {
              productionLineId:this.form.productLineId,
              moStatus:"生产中"
          }
          getWorkScheduleListByLineId(obj).then(response => {
              this.docNoList = response.data.data;
          })
          //根据产线ID获取产线详情
          getRealityProductLineDetailsList(this.form.productLineId).then(response => {
            var data =response.data.data;
            //子表数据
            this.lineDetailsList = data.realityProductLineDetailsList;//产线详情集合

          })
      },
      //工位选择
      chooseWorkstation(row){
        if(this.form.workPositionName!== row.workPositionName) {
          this.form.workPositionName = row.workPositionName;//工位名称
          this.processList = JSON.parse(row.workPositionProcessItem)
          this.form.processName=null;
          this.form.processId =null;
          this.form.workshopSection=null;
          this.wlItems = [];
          this.zzpItems = [];
          this.reworkItems = [];

        }

      },
      //工序选择
      chooseProcess(row){
        this.form.workshopSection = row.workshopSection;
        this.form.processName = row.processName;
        //根据工序ID查询不良项
        getBadItemByProcessId(row.id).then(response => {
          this.badItem=null;
          this.badItem = response.data.data.badItem;
          if(!this.validatenull(this.badItem)){
            const items = this.badItem.split(",");
            this.wlItems = items.map(item => ({ scrapReason: item, scrapQty: 0 }));
            this.zzpItems = items.map(item => ({ scrapReason: item, workInProgressScrapQty: 0 }));
            this.reworkItems = items.map(item => ({ reworkReason: item, reworkQty: 0 }));

          }
        })
      },
      // 报工提交
    onSubmits() {
          this.$refs.form.validate((valid) => {
              if (valid) {
                  const t = this;
                  this.$confirm('是否提交', '提示', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                  }).then(function () {
                    t.loading =true;
                     if(t.validatenull(t.form.workshopId)){
                       t.form.workshopName = null;
                     }
                    if(t.validatenull(t.form.productLineId)){
                      t.form.productLineName = null;
                    }
                    //1将form 深拷贝三份放入wlItems,zzpItems,reworkItems三个集合的每个对象中并且把数量是0的对象剔除
                    const formCopy = t.deepClone(t.form);

                    //2 过滤 wlItems、zzpItems 和 reworkItems 数组：
                    //从 t.wlItems 中过滤出 scrapQty 不为 null 且不为 0 的项，存储在 wlItems 变量中。
                    const wlItems = (t.wlItems || []).filter(item => item.scrapQty != null && item.scrapQty !== 0);
                    //从 t.zzpItems 中过滤出 workInProgressScrapQty 不为 null 且不为 0 的项，存储在 zzpItems 变量中。
                    const zzpItems = (t.zzpItems || []).filter(item => item.workInProgressScrapQty != null && item.workInProgressScrapQty !== 0);
                    //从 t.reworkItems 中过滤出 reworkQty 不为 null 且不为 0 的项，存储在 reworkItems 变量中
                    const reworkItems = (t.reworkItems || []).filter(item => item.reworkQty != null && item.reworkQty !== 0);

                    //3 将过滤后的 wlItems、zzpItems 和 reworkItems 数组转换为对象数组，每个对象包含 formCopy 和 item 的所有属性，存储在 wmsdList、wipsdList 和 preworkList 变量中。

                    //如果 wlItems 非空，则将 formCopy 合并到 wlItems 的每个对象中，生成新的数组 wmsdList；否则 wmsdList 为空数组。
                    const wmsdList = wlItems.length > 0 ? wlItems.map(item => ({ ...formCopy, ...item })) : [];
                    //如果 zzpItems 非空，则将 formCopy 合并到 zzpItems 的每个对象中，生成新的数组 wipsdList；否则 wipsdList 为空数组。
                    const wipsdList = zzpItems.length > 0 ? zzpItems.map(item => ({ ...formCopy, ...item })) : [];
                    //如果 reworkItems 非空，则将 formCopy 合并到 reworkItems 的每个对象中，生成新的数组 reworkList；否则 reworkList 为空数组。
                    const reworkList = reworkItems.length > 0 ? reworkItems.map(item => ({ ...formCopy, ...item })) : [];
                    //4 将 wmsdList、wipsdList 和 preworkList 数组合并成一个对象，并赋值给变量 obj。
                    var obj = {
                       workorderReport: {...t.form},//报工表
                       wmsdList:wmsdList,//报工物料明细
                       wipsdList:wipsdList,//报工在制品明细
                       reworkList:reworkList//报工返工明细
                    }
                    //调用保存接口
                     saveWorkOrderReport(obj).then(data => {
                       t.$message.success('提交成功')
                       t.resetForm();
                       t.loading =false;
                     }).catch(() => {
                         t.loading =false;
                       }
                     )
                  }).catch(() => {
                         t.loading =false;
                      }
                  )
              } else {
                  return false;
              }
          });
      },
      //表单重置
      resetForm(formName) {
          this.$refs.form.resetFields();
          this.wlItems = [];
          this.zzpItems = [];
          this.reworkItems = [];
          this.form.reportTime = null;
          this.form.workshopName = null;
          this.form.productLineName =null;
          this.form.productLineId =null;
          this.form.docNo =null;
          this.form.itemCode =null;
          this.form.workshopSection =null;
          this.form.processName=null;
          this.form.processId =null;
          this.form.workstation =  null;
          this.form.workshopName=null;
          this.form.workPositionId =  null;//工位ID
          this.form.workPositionName =  null;//工位名称

      },

    },
}
</script>
<style scoped>
  /deep/ .form-container {
    display: flex;
    justify-content: center;
    height: 800px;
    overflow: auto;
    /* 隐藏默认的滚动条样式 */
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */

    /* align-items: center;*/
    /* height: 100vh; 使用视窗高度来使得容器撑满整个屏幕 */
  }
  /deep/  .form-container::-webkit-scrollbar {
    display: none; /* Chrome, Safari, and Opera */
  }
    .inline-input-report1 {
/*    display: inline-block;
    width: 70%;
    margin-right: 2%;*/
  }
  .inline-input-report2 {
 /*   display: inline-block;
    width: 16%;*/
  }
</style>
